package it.koutifaris.travianmap.communication.urlverifier;

import it.koutifaris.travianmap.communication.AsyncResultHandler;

import java.net.URL;

import android.os.AsyncTask;
import android.util.Log;

public class UrlVerifierAsyncService extends AsyncTask<URL, Void, Boolean> {

	private static final String TAG = UrlVerifierAsyncService.class.getName();

	private final UrlVerifierService service;
	private VerificationHandler handler;
	private Throwable error;

	public UrlVerifierAsyncService() {
		service = new UrlVerifierService();
	}

	public void verifyResourceExists(URL url, VerificationHandler handler) {
		error = null;
		this.handler = handler;
		this.execute(url);
	}

	@Override
	protected Boolean doInBackground(URL... params) {
		Boolean result;
		try {
			result = service.verifyResourceExists(params[0]);
		} catch (Exception e) {
			Log.w(TAG, "verifyResourceExists error: " + e.getMessage(), e);
			error = e;
			result = null;
		}

		return result;
	}

	@Override
	protected void onPostExecute(Boolean result) {
		if (error != null) {
			handler.onError(error);
		} else {
			handler.onResult(result);
		}
	}

	public interface VerificationHandler extends AsyncResultHandler<Boolean> {

	}
}
